package com.kexinde.wjifen.action;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.kexinde.wjifen.config.CommonCfg;
import com.kexinde.wjifen.dao.ShopDao;
import com.kexinde.wjifen.dao.UserDao;
import com.kexinde.wjifen.model.Shop;
import com.kexinde.wjifen.model.User;
import com.kexinde.wjifen.util.MD5;
import com.kexinde.wjifen.vo.LoginUser;
import com.kexinde.wjifen.vo.RegistUser;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport implements RequestAware,
		SessionAware {

	private final static Logger logger = Logger.getLogger(UserAction.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 7389574991039306465L;

	private RegistUser registUser = null;
	private LoginUser loginUser = null;
	private Map<String, Object> request;
	private Map<String, Object> session;

	/**
	 * 登录
	 * 
	 * @return
	 */
	public String login() {
		try {
			User user = null;
			if (loginUser != null) {
				String inputCode = loginUser.getCode().toLowerCase(); // 用户输入的验证码
				String code = (String) session.get("code"); // 验证码，从session中取
				if (inputCode.equals(code)) {

					if (this.checkName(loginUser.getName())) { // 用户名正确
						String MD5Password = MD5.encryption(loginUser.getPassword());	//对输入密码加密
						logger.info(MD5Password);
						if (this.checkPassword(loginUser.getName(),MD5Password)) { // 用户密码正确
							UserDao userDao = new UserDao();
							user = userDao.findByName(loginUser.getName());
						} else { // 用户密码不正确

						}

					} else { // 用户名错误

					}

				} else { // 验证码错误
					request.put("errorCode", "验证码错误");
					logger.info("验证码错误");
				}
			} else { // loginUser为空，初始化失败

			}
			if (user != null) { // 用户登录成功
				session.put("user", user);
				session.put("myHotShops", this.getMyHotShops(user.getId()));	//拿我最常去商家
				
				if(loginUser.getAutoLogin()!=null){	//一个月内自动登录，写cookies
					
				}
				
				return SUCCESS;
			} else { // 登录失败
				return ERROR;
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ERROR;
	}

	/**
	 * 退出
	 * 
	 * @return
	 */
	public String logout() {
		try {
			if (session.get("user") != null) {
				session.remove("user");
				return SUCCESS;
			} else {
				return ERROR;
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return ERROR;
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	public String regist() {
		try {
			boolean result = false;
			User user = null;
			if (registUser != null) {
				String code = "1"; // 手机验证码，从session中取，保留60秒
				if (registUser.getCode().equals(code)) {
					if (registUser.getPassword().equals(
							registUser.getRepassword())) { // 判断密码和确认密码
						if (!this.checkName(registUser.getName())) {

							UserDao userDao = new UserDao();
							if (registUser.getRecommender() != null
									&& !registUser.getRecommender().equals("")) { // 若有推荐人

								if (this.checkName(registUser.getRecommender())) {// 推荐人正确
									registUser.setInitTotalPoint((CommonCfg.recommenderPoint));// 设置初始总分
									registUser.setPassword(MD5.encryption(registUser.getPassword()));	//MD5加密
									result = userDao.add(registUser);
									user = userDao.findByName(registUser.getName());
									logger.error("推荐人正确");
								} else { // 推荐人不正确
									logger.error("推荐人不正确");
								}

							} else { // 若无推荐人
								registUser.setPassword(MD5.encryption(registUser.getPassword()));	//MD5加密
								result = userDao.add(registUser);
								user = userDao.findByName(registUser.getName());
								logger.error("若无推荐人");
							}

						} else { // 用户名已存在
							logger.error("用户名已存在");
						}

					} else { // 密码与确认密码不同
						logger.error("密码与确认密码不同");
					}

				} else { // 验证码错误
					logger.error("验证码错误");
				}
			} else { // registUser为空，初始化失败
				logger.error("registUser为空，初始化失败");
			}
			if (result) { // 注册成功，并自动登录
				session.put("user", user);
				session.put("myHotShops", this.getMyHotShops(user.getId()));	//拿我最常去商家
			}
			// System.out.println(result);
			return result ? SUCCESS : ERROR;
		} catch (Exception e) {
			logger.error(e);
		}
		return ERROR;
	}

	/**
	 * 判断用户名是否已存在
	 * 
	 * @return 存在返回true,否则为false
	 */
	private boolean checkName(String name) {
		try {
			UserDao userDao = new UserDao();
			return userDao.isNameExist(name);
		} catch (Exception e) {
			logger.error(e);
		}
		return true;
	}

	/**
	 * 判断用户名密码是否正确
	 * 
	 * @return 正确为true,否则为false
	 */
	private boolean checkPassword(String name, String password) {
		try {
			UserDao userDao = new UserDao();
			return userDao.isPasswordRight(name, password);
		} catch (Exception e) {
			logger.error(e);
		}
		return false;
	}
	
	
	/**
	 * 判断微号是否重复
	 * 
	 * @return 重复为true,否则为false
	 */
	private boolean checkWeiNum(String weiNum) {
		try {
			UserDao userDao = new UserDao();
			return userDao.isWeiNumExist(weiNum);
		} catch (Exception e) {
			logger.error(e);
		}
		return false;
	}	
	
	/**
	 * 获取登录成功后首页16个个人商家
	 * @return
	 */
	private List<Shop> getMyHotShops(Long userId){
		try {
			ShopDao shopDao = new ShopDao();
			return shopDao.queryMyHotShops(userId);
		} catch (Exception e) {
			logger.error(e);
		}
		return null;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public void setRequest(Map<String, Object> request) {
		this.request = request;
	}

	public RegistUser getRegistUser() {
		return registUser;
	}

	public void setRegistUser(RegistUser registUser) {
		this.registUser = registUser;
	}

	public LoginUser getLoginUser() {
		return loginUser;
	}

	public void setLoginUser(LoginUser loginUser) {
		this.loginUser = loginUser;
	}
}
